﻿using System;

using Fuse8.DomainFramework.Common;

namespace Fuse8.ContentManagementFramework.Web.Etc
{
    public static class MementoExtensions
    {
        public static void SaveMemento<T>(this T obj, string key = null)
        {
            Guard.ArgumentNotNull(obj, "obj");

            var storage = new StorageFacade<ActionHistoryWatcher<T>>();

            var careTaker = new ActionHistoryWatcher<T>
            {
                Memento = obj
            };

            if (key == null)
            {
                storage.SetProperty(careTaker);    
            }
            else
            {
                storage.SetProperty(key, careTaker);
            }
            
        }

        public static T RestoreMemento<T>(this T obj, string key = null)
        {
            var storage = new StorageFacade<ActionHistoryWatcher<T>>();

            var careTaker = key == null ? storage.GetProperty() : storage.GetProperty(key);

            obj = careTaker.Memento;

            return obj;
        }

    }

    /// <summary>
    /// Memento
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ActionHistoryStorage<T>
    {
        public T State { get; internal set; }

        public ActionHistoryStorage(T value)
        {
            Guard.ArgumentNotNull(value, "value");

            State = value;
        }
    }

    /// <summary>
    /// CareTaker
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [Serializable]
    public class ActionHistoryWatcher<T>
    {
        public T Memento { get; set; }
    }
}
